package io.itit.ecp.admin.provide.action.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import icu.mhb.mybatisplus.plugln.core.JoinLambdaWrapper;
import icu.mhb.mybatisplus.plugln.extend.Joins;
import io.itit.ecp.admin.common.enums.IEarlyWarningRecordEnums;
import io.itit.ecp.admin.provide.action.req.EarlyWarningRecordQueryReq;
import io.itit.ecp.admin.provide.action.req.EarlyWarningRecordReq;
import io.itit.ecp.admin.provide.action.resp.EarlyWarningPushResp;
import io.itit.ecp.admin.provide.action.resp.EarlyWarningRecordResp;
import io.itit.ecp.admin.provide.filter.IEarlyWarningRecordFilter;
import io.itit.ecp.admin.provide.helper.SceneHelper;
import io.itit.ecp.admin.provide.renderer.EarlyWarningRecordRenderer;
import io.itit.ecp.admin.server.entity.*;
import io.itit.ecp.admin.server.service.IEarlyWarningPushService;
import io.itit.ecp.admin.server.service.IEarlyWarningRecordService;
import io.itit.grass.common.provide.action.req.BaseBatchIdReq;
import io.itit.grass.common.provide.action.req.BaseIdReq;
import io.itit.grass.common.provide.action.resp.ResultResp;
import io.itit.grass.common.provide.action.validation.*;
import io.itit.grass.common.server.utils.ConvertUtils;
import io.itit.grass.common.utils.Y666Utils;
import io.itit.grass.estelle.starter.core.ExcelXSSFUtil;
import io.itit.grass.estelle.starter.parse.ExcelParseManage;
import io.itit.grass.estelle.starter.util.JsonUtil;
import io.itit.grass.web.wall.utils.PageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 *
 * @Author：Roy
 * @Description：预警管理控制类
 * @Date：Create by 2023-12-15 11:20:26
 */
@Api(tags = "设备计量预警管理")
@RestController
@RequestMapping("/ecp-admin/earlyWarningRecord")
public class EarlyWarningRecordController {

    @Resource
    private IEarlyWarningRecordService earlyWarningRecordService;

    @Resource
    private IEarlyWarningPushService earlyWarningPushService;

    @ApiOperation("分页查询")
    @PostMapping("queryPage")
    @RequiresPermissions("ecp-admin:earlyWarningRecord:search")
    public ResultResp<IPage<EarlyWarningRecordResp>> queryPage(@RequestBody @Validated(IQueryPage.class) EarlyWarningRecordQueryReq req) {
        Page<EarlyWarningRecordResp> page = buildQW(req).joinPage(PageUtils.getPage(req, EarlyWarningRecordResp.class), EarlyWarningRecordResp.class);
        return ResultResp.success(SceneHelper.i().setSceneInfo(page));
    }

    @ApiOperation("详情")
    @PostMapping("detail")
    @RequiresPermissions("ecp-admin:earlyWarningRecord:search")
    public ResultResp<EarlyWarningRecordResp> detail(@RequestBody @Validated(IRequired.class) BaseIdReq req) {
        EarlyWarningRecordResp resp = ConvertUtils.copy(earlyWarningRecordService.getById(req.getId()), EarlyWarningRecordResp.class);
        List<EarlyWarningPushEntity> pushUsers = earlyWarningPushService.lambdaQuery().eq(EarlyWarningPushEntity::getEarlyWarningRecordId, req.getId()).list();
        resp.setPushUsers(ConvertUtils.convert(pushUsers, EarlyWarningPushResp.class));
        return ResultResp.success(resp);
    }

    /**
     * 组装查询条件
     *
     * @param req
     * @return
     */
    private static JoinLambdaWrapper<EarlyWarningRecordEntity> buildQW(EarlyWarningRecordQueryReq req) {
        return Joins.of(EarlyWarningRecordEntity.class)
                .leftJoin(SceneProjectEntity.class, SceneProjectEntity::getId, EarlyWarningRecordEntity::getSceneProjectId)
                .select(SceneProjectEntity::getProjectName)
                .end()
                .leftJoin(MeterDeviceEntity.class, MeterDeviceEntity::getId, EarlyWarningRecordEntity::getMeterDeviceId)
                .selectAs(t -> t.addFunAlias(MeterDeviceEntity::getDeviceCode, EarlyWarningRecordResp::getMeterDeviceCode)
                        .addFunAlias(MeterDeviceEntity::getDeviceName, EarlyWarningRecordResp::getMeterDeviceName))
                .end()
                .leftJoin(EnergyConsumptionTypeEntity.class, EnergyConsumptionTypeEntity::getId, EarlyWarningRecordEntity::getEnergyTypeId)
                .selectAs(EnergyConsumptionTypeEntity::getEnergyName, EarlyWarningRecordResp::getEnergyTypeName)
                .end()
                .leftJoin(SceneCompanyEntity.class, SceneCompanyEntity::getId, EarlyWarningRecordEntity::getSceneCompanyId)
                .selectAs(SceneCompanyEntity::getCompanyName, EarlyWarningRecordResp::getCompanyName)
                .end()
                .eq(StringUtils.isNotEmpty(req.getEarlyWarningId()), EarlyWarningRecordEntity::getEarlyWarningId, req.getEarlyWarningId())
                .eq(StringUtils.isNotEmpty(req.getWarningName()), EarlyWarningRecordEntity::getWarningName, req.getWarningName())
                .eq(EarlyWarningRecordEntity::getWarningType, IEarlyWarningRecordEnums.WarningType.warningType1.warningType)
                .in(CollectionUtils.isNotEmpty(req.getWarningTypeList()), EarlyWarningRecordEntity::getWarningType, req.getWarningTypeList())
                .eq(StringUtils.isNotEmpty(req.getSceneProjectId()), EarlyWarningRecordEntity::getSceneProjectId, req.getSceneProjectId())
                .eq(StringUtils.isNotEmpty(req.getSceneEdificeId()), EarlyWarningRecordEntity::getSceneEdificeId, req.getSceneEdificeId())
                .eq(StringUtils.isNotEmpty(req.getSceneFloorId()), EarlyWarningRecordEntity::getSceneFloorId, req.getSceneFloorId())
                .eq(StringUtils.isNotEmpty(req.getSceneRoomId()), EarlyWarningRecordEntity::getSceneRoomId, req.getSceneRoomId())
                .eq(StringUtils.isNotEmpty(req.getSceneCompanyId()), EarlyWarningRecordEntity::getSceneCompanyId, req.getSceneCompanyId())
                .eq(StringUtils.isNotEmpty(req.getMeterDeviceId()), EarlyWarningRecordEntity::getMeterDeviceId, req.getMeterDeviceId())
                .eq(StringUtils.isNotEmpty(req.getEnergyTypeId()), EarlyWarningRecordEntity::getEnergyTypeId, req.getEnergyTypeId())
                .eq(StringUtils.isNotEmpty(req.getMeterCondition()), EarlyWarningRecordEntity::getMeterCondition, req.getMeterCondition())
                .ge(StringUtils.isNotEmpty(req.getWarningDate()), EarlyWarningRecordEntity::getCreateTm, req.getWarningDate())
                .le(StringUtils.isNotEmpty(req.getWarningDate()), EarlyWarningRecordEntity::getCreateTm, Y666Utils.concat232359(req.getWarningDate()))
                .in(CollectionUtils.isNotEmpty(req.getMeterConditionList()), EarlyWarningRecordEntity::getMeterCondition, req.getMeterConditionList())
                .eq(StringUtils.isNotEmpty(req.getPushRule()), EarlyWarningRecordEntity::getPushRule, req.getPushRule())
                .in(CollectionUtils.isNotEmpty(req.getPushRuleList()), EarlyWarningRecordEntity::getPushRule, req.getPushRuleList())
                .eq(StringUtils.isNotEmpty(req.getJudgeRule()), EarlyWarningRecordEntity::getJudgeRule, req.getJudgeRule())
                .in(CollectionUtils.isNotEmpty(req.getJudgeRuleList()), EarlyWarningRecordEntity::getJudgeRule, req.getJudgeRuleList())
                .eq(req.getMeterValue() != null, EarlyWarningRecordEntity::getMeterValue, req.getMeterValue())
                .eq(req.getThresholdValue() != null, EarlyWarningRecordEntity::getThresholdValue, req.getThresholdValue())
                .eq(StringUtils.isNotEmpty(req.getThresholdUnit()), EarlyWarningRecordEntity::getThresholdUnit, req.getThresholdUnit())
                .eq(StringUtils.isNotEmpty(req.getThresholdLevel()), EarlyWarningRecordEntity::getThresholdLevel, req.getThresholdLevel())
                .in(CollectionUtils.isNotEmpty(req.getThresholdLevelList()), EarlyWarningRecordEntity::getThresholdLevel, req.getThresholdLevelList())
                .eq(StringUtils.isNotEmpty(req.getStatus()), EarlyWarningRecordEntity::getStatus, req.getStatus())
                .in(CollectionUtils.isNotEmpty(req.getStatusList()), EarlyWarningRecordEntity::getStatus, req.getStatusList())
                .eq(StringUtils.isNotEmpty(req.getDeptId()), EarlyWarningRecordEntity::getDeptId, req.getDeptId())
                .in(CollectionUtils.isNotEmpty(req.getIds()), EarlyWarningRecordEntity::getId, req.getIds())
                .last(StringUtils.isNotEmpty(req.getSortColumn()), PageUtils.lastOrderBy(req))
                .orderByDesc(StringUtils.isEmpty(req.getSortColumn()), EarlyWarningRecordEntity::getCreateTm);
    }

    @ApiOperation("新增")
    @PostMapping("add")
    @RequiresPermissions("ecp-admin:earlyWarningRecord:add")
    public ResultResp<Boolean> add(@RequestBody @Validated({IAdd.class}) EarlyWarningRecordReq req) {
        return ResultResp.success(earlyWarningRecordService.save(ConvertUtils.convertIgnoreId(req, EarlyWarningRecordEntity.class)));
    }

    @ApiOperation("编辑")
    @PostMapping("update")
    @RequiresPermissions("ecp-admin:earlyWarningRecord:update")
    public ResultResp<Boolean> update(@RequestBody @Validated({IUpdate.class}) EarlyWarningRecordReq req) {
        return ResultResp.success(earlyWarningRecordService.updateById(ConvertUtils.copy(req, EarlyWarningRecordEntity.class)));
    }

    @ApiOperation("删除(根据Id删)")
    @PostMapping("deleteById")
    @RequiresPermissions("ecp-admin:earlyWarningRecord:deleteById")
    public ResultResp<Boolean> deleteById(@RequestBody @Validated({IRequired.class}) BaseIdReq req) {
        return ResultResp.success(earlyWarningRecordService.removeById(req.getId()));
    }

    @ApiOperation("批量删除")
    @PostMapping("batchDelete")
    @RequiresPermissions("ecp-admin:earlyWarningRecord:batchDelete")
    public ResultResp<Boolean> batchDelete(@RequestBody @Validated({IRequired.class}) BaseBatchIdReq req) {
        return ResultResp.success(earlyWarningRecordService.removeBatchByIds(req.getIds(), 1000));
    }

    @ApiOperation("导入")
    @PostMapping("upload")
    @RequiresPermissions("ecp-admin:earlyWarningRecord:upload")
    public ResultResp<Integer> upload(@RequestParam("file") MultipartFile file, Boolean ignoreError) {
        return ResultResp.success(ExcelParseManage.i().process(EarlyWarningRecordRenderer.ENTITY_NAME, file, ignoreError));
    }

    @ApiOperation("导出")
    @PostMapping("export")
    @RequiresPermissions("ecp-admin:earlyWarningRecord:export")
    public void export(@RequestBody @Validated(IExport.class) EarlyWarningRecordQueryReq req, HttpServletResponse response) {
        ExcelXSSFUtil.export("EarlyWarningRecordExport", JsonUtil.toJson(earlyWarningRecordService.list(buildQW(req)), new IEarlyWarningRecordFilter.EarlyWarningRecordExportFilter()), response);
    }
}
